<template>
  <div class="app-container">
    <div style="background-color: #fff">
      <div class="container-module" style="padding-bottom: 0">
        <el-form :inline="true" class="search-form" size="small">
          <el-row style="display: flex">
            <div style="flex: 1">
              <el-form-item
                class="search-form-item"
                v-if="administrators"
                label="供应商id"
                style="margin: 5px 0"
              >
                <el-select
                  style="width: 100%"
                  clearable
                  v-model="searchForm.supplier_id"
                  filterable
                  placeholder="请输入供货商名称搜索"
                >
                  <el-option
                    v-for="item in SupplierList"
                    :key="item.id"
                    :label="item.supplier_name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item
                class="search-form-item"
                label="手机号"
                style="margin: 5px 0"
              >
                <el-input
                  clearable
                  placeholder="请输入手机号"
                  v-model="searchForm.phone_number"
                  type="text"
                  min="1"
                  class="input-with-select"
                >
                </el-input>
              </el-form-item>
            </div>
            <div style="padding: 5px 0">
              <el-form-item>
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-search"
                  @click="getListWay"
                  >查询</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-refresh"
                  @click="resetting"
                  >重置</el-button
                >
                <el-button
                  v-if="!searchDisplay"
                  size="small"
                  icon="el-icon-caret-bottom"
                  @click="searchDisplay = true"
                  >展开</el-button
                >
                <el-button
                  v-else
                  size="small"
                  icon="el-icon-caret-top"
                  @click="searchDisplay = false"
                  >收起</el-button
                >
              </el-form-item>
            </div>
          </el-row>
          <el-row v-if="searchDisplay" style="display: flex">
            <el-form-item
              class="search-form-item"
              label="收货人姓名"
              style="margin: 5px 0"
            >
              <el-input
                clearable
                placeholder="请输入收货人姓名"
                v-model="searchForm.recipient"
                type="text"
                min="1"
                class="input-with-select"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              class="search-form-item"
              label="是否默认"
              style="margin: 5px 0"
            >
              <el-select
                style="width: 100%"
                clearable
                v-model="searchForm.is_default"
                filterable
                placeholder="请输入供货商名称搜索"
              >
                <el-option
                  v-for="item in [
                    { id: '1', name: '默认' },
                    { id: '2', name: '非默认' },
                  ]"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              class="search-form-item"
              label="省份"
              style="margin: 5px 0"
            >
              <el-select
                @change="provinceWay"
                v-model="searchForm.province_id"
                placeholder="请选择省份"
              >
                <el-option
                  v-for="item in provinceList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              class="search-form-item"
              label="城市"
              style="margin: 5px 0"
            >
              <el-select
                :disabled="cityList.length == 0"
                @change="cityWay"
                v-model="searchForm.city_id"
                placeholder="请选择城市(请先选择省份)"
              >
                <el-option
                  v-for="item in cityList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              class="search-form-item"
              label="请选择区县"
              style="margin: 5px 0"
            >
              <el-select
                :disabled="districtList.length == 0"
                v-model="searchForm.distrrict_id"
                placeholder="请选择区县(请先选择城市)"
              >
                <el-option
                  v-for="item in districtList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <el-divider></el-divider>
      <div style="padding: 0 20px">
        <div class="marginBottom">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-button
                @click="addWay"
                v-hasPermi="'address/add'"
                icon="el-icon-circle-plus-outline"
                type="primary"
                >添加地址</el-button
              >
            </el-col>
            <el-col :span="4" style="float: right">
              <div class="right-panel el-button-group">
                <el-button
                  class=""
                  icon="el-icon-refresh"
                  size="mini"
                  @click="getListWay"
                ></el-button>
                <el-dropdown trigger="click" :hide-on-click="false">
                  <span class="el-dropdown-link">
                    <el-button
                      class=""
                      icon="el-icon-s-operation"
                      size="mini"
                    ></el-button>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="fruit in allTableThead"
                      :key="fruit"
                    >
                      <el-checkbox
                        v-model="checkboxTableThead"
                        :label="fruit"
                        >{{ tableTheadOptions[fruit].label }}</el-checkbox
                      >
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row :gutter="20">
          <el-col class="new_table_card">
            <el-table
              ref="tablerefs"
              highlight-current-row
              :data="AddressList"
              :header-cell-style="{
                'background-color': '#f3f8fe',
                color: '#606266',
                height: '50px',
              }"
              style="width: 100%"
              height="100%"
              v-loading="loading"
            >
              <el-table-column
                v-for="fruit in tableThead"
                :key="fruit"
                :label="tableTheadOptions[fruit].label"
                :width="
                  tableTheadOptions[fruit].width
                    ? tableTheadOptions[fruit].width + 'px'
                    : 'auto'
                "
                min-width="80"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="fruit == 'is_default'">
                    <span v-if="scope.row[fruit] == 1" style="color: #0076f6;"
                      >默认地址</span
                    >
                    <span v-if="scope.row[fruit] == 2">否</span>
                  </div>
                  <div v-else-if="fruit == 'province_name'">
                    {{ scope.row.province_name ? scope.row.province_name : "" }}
                    {{ scope.row.city_name ? scope.row.city_name : "" }}
                    {{ scope.row.district_name ? scope.row.district_name : "" }}
                  </div>
                  <span v-else>
                    <el-tooltip
                      placement="top"
                      :content="
                        scope.row[fruit] ? scope.row[fruit].toString() : '-'
                      "
                    >
                      <div class="one_line_hidden">
                        {{ scope.row[fruit] ? scope.row[fruit] : "-" }}
                      </div>
                    </el-tooltip>
                  </span>
                </template>
              </el-table-column>

              <el-table-column
                align="center"
                fixed="right"
                width="200"
                prop="address"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    v-hasPermi="'address/edit'"
                    size="mini"
                    @click="editWay(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-divider direction="vertical"></el-divider>
                  <el-popconfirm
                    title="这是一段内容确定删除吗？"
                    @confirm="delWay(scope.row)"
                  >
                    <el-button
                      v-hasPermi="'address/del'"
                      type="text"
                      size="mini"
                      slot="reference"
                    >
                      删除
                    </el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table></el-col
          >
        </el-row>
        <el-row style="text-align: right">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="searchForm.page"
            :limit.sync="searchForm.count"
            @pagination="getListWay"
          />
        </el-row>
      </div>
    </div>

    <el-drawer
      id="drawer"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="添加/编辑收货地址"
      size="55%"
      :withHeader="false"
      :visible.sync="addressDialog"
      @close="addressClose"
      :show-close="true"
    >
      <div style="position: relative" v-loading="addressLoading">
        <div class="drawerTitle" id="drawerTitle">
          <span>供应商收货地址-添加/编辑</span>
          <div class="close" @click="addressClose">
            <i class="el-icon-close" style="font-size: 24px;"></i>
          </div>
        </div>
        <el-alert
          id="prompt_explanation"
          class="prompt_explanation"
          title="说明：如平台用户或商户产生退换货时,可根据供应商提供的退货地址进行退回！"
          type="warning"
          :closable="false"
        >
        </el-alert>
        <el-scrollbar
          wrap-style="overflow-x:hidden;"
          :style="'height:' + reduce"
        >
          <div class="informationTitleView">
            <div class="leftBox">
              <div class="leftborder"></div>
              <div class="text">收货人信息</div>
            </div>
            <div class="right"></div>
          </div>
          <el-row>
            <el-form
              ref="addressForm"
              :rules="addressRules"
              :model="addressForm"
              label-width="120px"
            >
              <el-col :span="22" v-if="administrators">
                <el-form-item label="关联供货商" prop="supplier_id">
                  <el-select
                    style="width: 100%"
                    v-model="addressForm.supplier_id"
                    filterable
                    placeholder="请输入供货商名称搜索"
                  >
                    <el-option
                      v-for="item in SupplierList"
                      :key="item.id"
                      :label="item.supplier_name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="收货人" prop="recipient">
                  <el-input
                    maxlength="10"
                    show-word-limit
                    v-model="addressForm.recipient"
                    placeholder="请输入收货人"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="联系电话" prop="phone_number">
                  <el-input
                    maxlength="11"
                    show-word-limit
                    v-model="addressForm.phone_number"
                    placeholder="请输入联系电话"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div class="informationTitleView">
                  <div class="leftBox">
                    <div class="leftborder"></div>
                    <div class="text">地址信息</div>
                  </div>
                  <div class="right"></div>
                </div>
              </el-col>
              <el-col :span="11">
                <el-form-item label="省份" prop="province_id">
                  <el-select
                    @change="provinceWay"
                    v-model="addressForm.province_id"
                    placeholder="请选择省份"
                  >
                    <el-option
                      v-for="item in provinceList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="城市" prop="city_id">
                  <el-select
                    :disabled="cityList.length == 0"
                    @change="cityWay"
                    v-model="addressForm.city_id"
                    placeholder="请选择城市(请先选择省份)"
                  >
                    <el-option
                      v-for="item in cityList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="区/县" prop="district_id">
                  <el-select
                    :disabled="districtList.length == 0"
                    v-model="addressForm.district_id"
                    placeholder="请选择区县(请先选择城市)"
                  >
                    <el-option
                      v-for="item in districtList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="详细地址" prop="address_details">
                  <el-input
                    maxlength="50"
                    show-word-limit
                    v-model="addressForm.address_details"
                    placeholder="请输入详细地址"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="是否默认" prop="is_default">
                  <el-radio-group v-model="addressForm.is_default">
                    <el-radio :label="1">默认</el-radio>
                    <el-radio :label="2">非默认</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注说明" prop="explain">
                  <el-input
                    type="textarea"
                    placeholder="请输入..."
                    v-model="addressForm.explain"
                    style="width: calc(100% - 30px)"
                    :autosize="{ minRows: 4, maxRows: 6 }"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </el-scrollbar>
        <el-row style="margin: 20px 0">
          <el-col :span="24" style="text-align: right; padding-right: 30px">
            <el-button :loading="addressLoading" @click="addressDialog = false"
              >取 消</el-button
            >
            <el-button
              :loading="addressLoading"
              type="primary"
              @click="addressSubmit('form')"
              >保 存</el-button
            >
          </el-col>
        </el-row>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getRegionList } from "@/api/user/index";
import { querySupplierList, getInfo } from "@/api/index";
import {
  getPublicSupplierAddressList,
  SaveSupplierAddress,
  delSupplierAddress,
  getSupplierAddressInfo,
} from "@/api/supplier/index";
const tableTheadOption = {
  id: {
    label: "ID",
    field: "id",
  },
  supplier_name: {
    label: "供货商名称",
    field: "supplier_name",
  },
  recipient: {
    label: "收货人名称",
    field: "recipient",
  },
  phone_number: {
    label: "手机号",
    field: "phone_number",
  },
  province_name: {
    label: "省市区",
    field: "province_name",
    width: 150,
  },
  address_details: {
    label: "详细地址",
    field: "address_details",
  },
  is_default: {
    label: "是否默认",
    field: "is_default",
  },
};
const allTableThead = [
  "id",
  "supplier_name",
  "recipient",
  "phone_number",
  "province_name",
  "address_details",
  "is_default",
];
const defaultTableThead = [
  "id",
  "supplier_name",
  "recipient",
  "phone_number",
  "province_name",
  "address_details",
  "is_default",
];
export default {
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(
        (i) => valArr.indexOf(i) >= 0
      );
      this.tableKey = this.tableKey + 1;
      this.$nextTick(() => {
        this.$refs.tablerefs.doLayout();
      });
    },
  },
  data() {
    return {
      reduce: 0,
      // 默认表头
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值
      tableKey: 1, // 为了保证table 每次都会重渲
      loading: false,
      searchDisplay: false,
      userInfo: {}, // 用户信息
      administrators: false, // 当前登录用户是否是管理员
      SupplierList: [], // 供应商列表
      provinceList: [], // 省份列表
      cityList: [], // 城市列表
      districtList: [], // 区县列表
      addressshow:{},
      searchForm: {
        supplier_id: "", // 供应商id
        recipient: "", // 收货人姓名
        phone_number: "", // 手机号
        is_default: "", // 是否默认 1默认 2不默认
        province_id: "", // 类型 1省 2市 3区
        city_id: "", // 值
        district_id: "", // 值
        page: 1,
        count: 20,
      },
      total: 0,
      AddressList: [],
      title: "添加地址",
      addressForm: {
        recipient: "",
        phone_number: "",
        province_id: "",
        city_id: "",
        district_id: "",
        address_details: "",
        is_default: 2,
        id: "",
        supplier_id: "",
      },

      addressRules: {
        supplier_id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("供货商id不能为空"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        recipient: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请填写收货人姓名"));
              }
              var reg = /[^a-zA-Z\u4e00-\u9fa5]/g;
              if (reg.test(value)) {
                return callback(
                  new Error("姓名中不能带有特殊字符和阿拉伯数字")
                );
              }
              callback();
            },
            trigger: "change",
          },
        ],
        phone_number: [
          {
            required: true,
            validator: (rule, value, callback) => {
              var reg = /^1[3456789]\d{9}$/;
              if (!reg.test(value)) {
                return callback(new Error("手机号格式不正确"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        province_id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请选择省份"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        city_id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请选择城市"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        district_id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请选择区县"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        address_details: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请输入详细地址"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
      addressDialog: false,
      addressLoading: false,
    };
  },
  created(args) {
    var _this = this;
    _this.loading = true;

    let p1 = new Promise((req, rej) => {
      if (localStorage.getItem("region")) {
        _this.provinceList = JSON.parse(localStorage.getItem("region"));
        req();
      } else {
        getRegionList().then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.$messages.error(res.msg);
            rej();
          }
          _this.provinceList = res.data;
          localStorage.setItem(
            "region",
            JSON.stringify(res.data)
          );
          req();
        });
      }
    });
    let p2 = new Promise((req, rej) => {
      querySupplierList().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          rej();
        }
        _this.SupplierList = res.data;
        req();
      });
    });
    let p3 = new Promise((req, rej) => {
      getInfo().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          rej();
        }
        _this.userInfo = res.data;
        if (_this.userInfo.supplier_id == 0 || _this.userInfo.supplier_id) {
          _this.administrators = true;
          console.log("11");
        } else {
          _this.administrators = false;
          _this.searchForm.supplier_id = _this.userInfo.supplier_id;
          _this.addressForm.supplier_id = _this.userInfo.supplier_id;
        }

        req();
      });
    });
    Promise.all([p1, p2, p3])
      .then((res) => {
        this.getListWay();
      })
      .catch(() => {
        _this.loading = false;
      });
  },
  methods: {
    nextTickWay(idName1, idName2, idName3) {
      this.$nextTick(() => {
        var adddialogVisible = document.getElementById(idName1);
        var drawerTitle = document.getElementById(idName2);
        var prompt_explanation = document.getElementById(idName3);
        this.reduce =
          adddialogVisible.offsetHeight -
          (prompt_explanation.offsetHeight + drawerTitle.offsetHeight + 100) +
          "px";
      });
    },
    getListWay() {
      this.loading = true;
      this.searchDisplay = false;
      getPublicSupplierAddressList(this.searchForm).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.loading = false;
          return this.$messages.error(res.msg);
        }
        this.AddressList = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    resetting() {
      this.searchForm = {
        supplier_id: "", // 供应商id
        recipient: "", // 收货人姓名
        phone_number: "", // 手机号
        is_default: 2, // 是否默认 1默认 2不默认
        province_id: "", // 类型 1省 2市 3区
        city_id: "", // 值
        distrrict_id: "", // 值
        page: 1,
        count: 20,
      };
      this.getListWay();
    },
    provinceWay(val) {
      let cityshow = val
      if(cityshow != this.addressshow.province_id){
        this.addressForm.city_id = "";
        this.addressForm.district_id = "";
      }
      this.cityList = []
      this.districtList = []
      this.provinceList.forEach((item) => {
        if (item.id == val) {
          this.cityList = item.children;
        }
        this.$forceUpdate();
      });
    },
    cityWay(val) {
      let cityshow = val
      if(cityshow != this.addressshow.city_id){
        this.addressForm.district_id = "";
      }
      this.addressForm.city_id = val

      this.districtList = []
      this.cityList.forEach((item) => {
        if (item.id == val) {
          this.districtList = item.children;
        }
      });

      this.$forceUpdate();
    },
    addWay() {
      this.districtList = []
      this.cityList = []
      this.addressDialog = true;
      this.nextTickWay("drawer", "drawerTitle", "prompt_explanation");
    },
    addressClose() {
      this.addressForm = {
        recipient: "",
        phone_number: "",
        province_id: "",
        city_id: "",
        district_id: "",
        address_details: "",
        is_default: 2,
        id: "",
        supplier_id: "",
      };
      this.$refs.addressForm.resetFields();
      this.addressDialog = false;
    },
    editWay(row) {
      this.addressDialog = true;
      this.addressLoading = true;
      getSupplierAddressInfo({ id: row.id, supplier_id: row.supplier_id }).then(
        (res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.addressLoading = false;
            return this.$messages.error(res.msg);
          }
          this.provinceWay(row.province_id);
          this.cityWay(row.city_id);
          this.addressForm = JSON.parse(JSON.stringify(row));
          this.addressshow = JSON.parse(JSON.stringify(row));
          this.addressLoading = false;
          this.nextTickWay("drawer", "drawerTitle", "prompt_explanation");
        }
      );
    },
    delWay(row) {
      this.loading = true;
      delSupplierAddress({ id: row.id })
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.$messages.success("删除成功");
          this.getListWay();
        })
        .catch((err) => {
          this.loading = false;
          this.$messages.error(err.msg);
        });
    },
    addressSubmit() {
      console.log(this.addressForm,"787978")
      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          this.addressLoading = true;
          SaveSupplierAddress(this.addressForm).then((res) => {
            if (res.code !== 200 || res.status !== 1) {
              this.addressLoading = false;
              return this.$messages.error(res.msg);
            }
            this.$messages.success(res.msg);
            this.addressLoading = false;
            this.addressClose();
            this.addressDialog = false;
            this.getListWay();
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>
